package com.mikhailenko.transportMVC.service.es.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mikhailenko.transportMVC.exeption.es.InputNotFoundException;
import com.mikhailenko.transportMVC.model.es.InputEntity;
import com.mikhailenko.transportMVC.repository.es.InputRepository;
import com.mikhailenko.transportMVC.service.es.InputService;

@Service
public class InputServiceImpl implements InputService {

    @Autowired
    private InputRepository inputRepository;
    
    @Override
    public InputEntity create(InputEntity input) {
        InputEntity createdInput = input;
        return inputRepository.saveAndFlush(createdInput);
    }

    @Override
    public InputEntity delete(int id) throws InputNotFoundException {
        InputEntity deletedInput = inputRepository.findOne(id);
        
        if (deletedInput == null){
            throw new InputNotFoundException();
        }
        
        inputRepository.delete(deletedInput);
        return deletedInput;
    }

    @Override
    public List<InputEntity> findAll() {
        return inputRepository.findAll();
    }

    @Override
    public InputEntity update(InputEntity input) throws InputNotFoundException {
        InputEntity updatedInput = inputRepository.findOne(input.getId());
        
        if (updatedInput == null){
            throw new InputNotFoundException();
        }
        
        updatedInput.setType(input.isType());
        updatedInput.setName(input.getName());
        updatedInput.setTerm(input.getTerm());
        updatedInput.setUsed(input.isUsed());
        updatedInput.setBlock(input.getBlock());
        
        return updatedInput;
    }

    @Override
    public InputEntity findById(int id) {
        return inputRepository.findOne(id);
    }

	@Override
	public InputEntity findByName(String name) {
		return inputRepository.findByName(name);
	}

	@Override
	public List<InputEntity> findByBlockId(int id) {
		return inputRepository.findByBlockId(id);
	}

}
